package com.songshuai.webapi.permission.controller;

import com.songshuai.webapi.baseapi.annotations.SysLogger;
import com.songshuai.webapi.baseapi.dto.UserBaseInfoDto;
import com.songshuai.webapi.baseapi.dto.UserUpdatePwdDto;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.utils.EncryptUtil;
import com.songshuai.webapi.baseapi.utils.RegexUtil;
import com.songshuai.webapi.baseapi.utils.RequestParamValidUtil;
import com.songshuai.webapi.permission.dto.request.*;
import com.songshuai.webapi.permission.dto.response.RolesLoginResDto;
import com.songshuai.webapi.permission.dto.response.UserResDto;
import com.songshuai.webapi.permission.model.YxUsers;
import com.songshuai.webapi.permission.service.UsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Api("用户管理")
@Slf4j
@RestController
@RequestMapping("/api/users/")
public class UsersController extends BaseController{
    @Autowired
    private UsersService usersService;
   /* @Autowired
    CustomLog logst;*/




    @ApiOperation(value = "根据登录用户获取菜单和功能")
    @PostMapping("queryLoginNavAndFunc")
    public QueryResponse<Map<String,Object>> queryLoginNavAndFunc(@RequestParam("appId") Integer appId){
        Map<String,Object> result = usersService.queryLoginNavAndFunc(appId);
        return QueryResponse.setResData(result, ResultStatus.SUCCESS);
    }

    //@Cacheable(value = "queryUserById")
    @ApiOperation(value = "根据id获取用户信息")
    @GetMapping("queryUserById")
   // @SysLogger(operation = "根据id查用户",value = "queryUserById")
    public QueryResponse queryUserById(@RequestParam("id") Integer id){
        boolean lock = getTokenLock("/api/users/queryUserById");
        try {
            if(lock){
//              logst.info(this.getClass().getName(),"====这是一个测试参数的实验","参数hahaha");
                UserResDto resDto = usersService.queryUserById(id);
                return QueryResponse.setResData(resDto, ResultStatus.SUCCESS);
            }
        } catch (Exception e){
            e.printStackTrace();
            //logst.error(this.getClass().getName(),"查询用户异常",e);
            logger.error("queryUserById",e);
        } finally {
            relesesTokenLock("/api/users/queryUserById");
        }
        return QueryResponse.setResData(new UserResDto(),ResultStatus.HTTP_STATUS_BAD_REQUEST);
    }
    @ApiOperation(value = "编辑用户信息")
    @PostMapping("updateUser")
    public QueryResponse updateUser(@Valid @RequestBody UserUpdateReqDto parmDto, BindingResult result){
        if (result.hasErrors() || (StringUtils.isBlank(parmDto.getMobile()) && StringUtils.isBlank(parmDto.getEmail()))) {
            //手机号和邮箱不能同时为空
            return new QueryResponse(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
        }
        boolean lock = getTokenLock("/api/users/updateUser");
        try {
            if(lock){
                boolean isSucc = usersService.updateUser(parmDto);
                if(isSucc){
                    return new QueryResponse();
                }
            }
        } finally {
            relesesTokenLock("/api/users/updateUser");
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);
    }
    @ApiOperation(value = "移出部门")
    @GetMapping("deleteDepartmentUserRelation")
    public QueryResponse deleteDepartmentUserRelation(@RequestParam("userId")Integer userId,@RequestParam("departmentId")Integer departmentId){
        boolean isSucc = usersService.deleteDepartmentUserRelation(userId,departmentId);
        if(isSucc){
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_DELETE_FAILED);
    }

    @ApiOperation(value = "员工离职/入职")
    @PostMapping("updateUserLeave")
    public QueryResponse updateUserLeave(@Valid @RequestBody UserUpdateLeaveReqDto parmDto, BindingResult result){
        try {
            if (result.hasErrors()){
                return new QueryResponse(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
            }
            boolean isSucc = usersService.updateUserLeave(parmDto);
            if(isSucc){
                return new QueryResponse();
            }
        } catch (Exception e) {
            log.error("updateUserLeave",e);
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);
    }

    @ApiOperation(value = "查询登录用户的角色")
    @GetMapping("queryLoginRolesList")
    public QueryResponse<List<RolesLoginResDto>> queryLoginRolesList(@RequestParam("userId")Integer userId){
        List<RolesLoginResDto> roleList = usersService.queryLoginRolesList(userId);
        return QueryResponse.setResData(roleList, ResultStatus.SUCCESS);
    }

    @ApiOperation(value = "分配角色")
    @PostMapping("addUserRoleRelation")
    public QueryResponse addUserRoleRelation(@Valid @RequestBody UserRelateRoleReqDto parmDto, BindingResult result){
        if (result.hasErrors()) {
            return new QueryResponse(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
        }
        boolean lock = getTokenLock("/api/users/addUserRoleRelation");
        try {
            if(lock) {
                boolean isSucc = usersService.addUserRoleRelation(parmDto);
                if (isSucc) {
                    return new QueryResponse();
                }
            }
        } catch (Exception e) {
            log.error("addUserRoleRelation",e);
        } finally {
            relesesTokenLock("/api/users/addUserRoleRelation");
        }
        return new QueryResponse(ResultStatus.ERROR_CREATE_FAILED);
    }

    @ApiOperation(value = "查询登录用户的权限并对当前用户已分配权限返填")
    @GetMapping("queryLoginNavAndFuncList")
    public QueryResponse<Map<String,Object>> queryLoginNavAndFuncList(@RequestParam("userId")Integer userId,@RequestParam("appId")Integer appId){
        Map<String,Object> result = usersService.queryLoginNavAndFuncList(userId,appId);
        return QueryResponse.setResData(result, ResultStatus.SUCCESS);
    }

    @ApiOperation(value = "分配权限")
    @PostMapping("addUserNavigationRelation")
    public QueryResponse addUserNavigationRelation(@Valid @RequestBody UserRelateNavigationReqDto parmDto, BindingResult result){
        if (result.hasErrors()) {
            return new QueryResponse(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
        }
        boolean lock = getTokenLock("/api/users/addUserNavigationRelation");
        try {
            if(lock) {
                boolean isSucc = usersService.addUserNavigationRelation(parmDto);
                if (isSucc) {
                    return new QueryResponse();
                }
            }
        } catch (Exception e) {
            log.error("addUserNavigationRelation",e);
        } finally {
            relesesTokenLock("/api/users/addUserNavigationRelation");
        }
        return new QueryResponse(ResultStatus.ERROR_CREATE_FAILED);
    }

    @ApiOperation(value = "重置密码")
    @GetMapping("resetPwd")
    public QueryResponse resetPwd(@RequestParam("id") Integer id){
        boolean isSucc = usersService.resetPwd(id);
        if(isSucc) {
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);
    }



    @ApiOperation(value = "修改密码")
    @PostMapping("updatePwd")
    public QueryResponse updatePwd(@RequestBody @Valid UserUpdatePwdReqDto request, BindingResult result){
        if (result.hasErrors()){
            return new QueryResponse(ResultStatus.SUCCESS.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
        }
        if(!request.getNewPwd().equals(request.getConfirmPwd())){
            return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED.getErrorCode(),"两次密码输入不一致");
        }
        YxUsers yxUsers = getUserBaseInfo();
        String pwd = EncryptUtil.md5(request.getOldPwd()).substring(0, 20);
        if (!pwd.equalsIgnoreCase(yxUsers.getPassword())){
            return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED.getErrorCode(),"旧密码输入错误");
        }
        boolean b = usersService.updateByPrimaryKeySelective(new YxUsers() {{
            setId(yxUsers.getId());
            setPassword(EncryptUtil.md5(request.getNewPwd()).substring(0, 20).toUpperCase());
        }});
        if (b){
            redisUtil.del(getUserName());
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);
    }
    @ApiOperation(value = "修改密码")
    @PostMapping("updateUserPwd")
    public QueryResponse updatePwd(@RequestBody UserUpdatePwdDto request){
        YxUsers yxUsers = getUserBaseInfo();
        logger.info(request.toString());
        String pwd = EncryptUtil.md5(request.getOldPwd()).substring(0, 20);
        if (!pwd.equalsIgnoreCase(yxUsers.getPassword())){
            return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED.getErrorCode(),"旧密码输入错误");
        }
        boolean b = usersService.updateByPrimaryKeySelective(new YxUsers() {{
            setId(yxUsers.getId());
            setPassword(EncryptUtil.md5(request.getNewPwd()).substring(0, 20).toUpperCase());
        }});
        if (b){
            redisUtil.del(getUserName());
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);
    }


    @ApiOperation(value = "查询登录用户菜单并对当前用户已配置首页返填")
    @GetMapping("queryLoginHomePageList")
    public QueryResponse<Map<String,Object>> queryLoginHomePageList(@RequestParam("userId")Integer userId,@RequestParam("appId")Integer appId){
        Map<String,Object> result = usersService.queryLoginHomePageList(userId,appId);
        return QueryResponse.setResData(result, ResultStatus.SUCCESS);
    }

    @ApiOperation(value = "用户首页配置")
    @PostMapping("addHomePage")
    public QueryResponse addHomePage(@Valid @RequestBody HomepageConfigReqDto parmDto, BindingResult result){
        if (result.hasErrors()) {
            return new QueryResponse(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
        }
        boolean lock = getTokenLock("/api/users/addHomePage");
        try {
            if(lock) {
                boolean isSucc = usersService.addHomePage(parmDto);
                if (isSucc) {
                    return new QueryResponse();
                }
            }
        } catch (Exception e) {
            log.error("addHomePage",e);
        } finally {
            relesesTokenLock("/api/users/addHomePage");
        }
        return new QueryResponse(ResultStatus.ERROR_CREATE_FAILED);
    }

    @GetMapping("getCurrentUser")
    @Cacheable(value = "getCurrentUser")
    public QueryResponse getCurrentUser(@RequestParam("username") String username){
        if(StringUtils.isBlank(username)){
            return null;
        }
        int integer = RegexUtil.validPhoneOrMail(username);
        YxUsers user = usersService.getCurrentUser(integer, username);
        if(null!=user){
            return  QueryResponse.setResData(user,0,"查询成功");
        }else{
            return new QueryResponse(1,"无正确用户");
        }
    }

    /**
     * 根据校区id获取用户
     * @param campusId
     * @return
     */
   // @Cacheable(value = "getUsersByCampusId")
    @ApiOperation(value = "根据校区id获取用户列表")
    @GetMapping("getUsersByCampusId")
    public QueryResponse getUsersByCampusId(@RequestParam("id") Integer campusId,@RequestParam(value = "isAll",required = false) Boolean isAll){
        if(campusId==null||campusId<=0) {
            return QueryResponse.setResData(null);
        }
        try{
            List<UserBaseInfoDto>userList = usersService.getUsersByCampusId(campusId,isAll);
            return QueryResponse.setResData(userList);
        }catch (Exception ex){
            return  QueryResponse.setResData(null,ResultStatus.HTTP_STATUS_INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }

    @ApiOperation(value = "根据用户id获取用户列表")
    @PostMapping("getUsersByUserIds")
    public QueryResponse getUsersByUserIds(@RequestBody List<Integer> userIds){
        if(userIds==null||userIds.size()==0) {
            return QueryResponse.setResData(null);
        }
        try{
            List<UserBaseInfoDto>userList = usersService.getUsersByIds(userIds);
            return QueryResponse.setResData(userList);
        }catch (Exception ex){
            return  QueryResponse.setResData(null,ResultStatus.HTTP_STATUS_INTERNAL_SERVER_ERROR,ex.getMessage());
        }
    }

}
